#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/20 14:47
# @Author  : huidong.bai
# @File    : usb_monitor.py
# @Software: PyCharm

import time
import os
import sys
from ctypes import wintypes
from threading import Thread

from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QPlainTextEdit
from PyQt5.QtCore import pyqtSignal

import serial.tools.list_ports
import platform
import win32com.client

# USB设备发生变化表示
WM_DEVICECHANGE = 0x0219
DBT_DEVICEREMOVECOMPLETE = 0x8004
DBT_DEVICEARRIVAL = 0x8000

# GUID = {88bae032-5a81-49f0-bc3d-a4ff138216d6}


class Window(QWidget):
    update_device = pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self.resize(500, 300)
        self.setWindowTitle('USB监听器')
        self.lab_sn = QLabel(self)
        self.lab_sn.move(80, 70)
        self.lab_sn.setText('日志记录')
        # 自动换行，添加纯文本内容
        self.text_edit = QPlainTextEdit(self)
        self.text_edit.move(150, 70)
        self.text_edit.resize(300, 200)
        self.update_device.connect(self.onUpdateDevices)

    def nativeEvent(self, eventType, message):
        tag, result = super().nativeEvent(eventType, message)
        if eventType == "windows_generic_MSG":
            msg = wintypes.MSG.from_address(message.__int__())

            # 查询设备列表
            if msg.message == WM_DEVICECHANGE:
                if DBT_DEVICEARRIVAL == msg.wParam or DBT_DEVICEREMOVECOMPLETE == msg.wParam:
                    print('准备好了')

                    def task(sign):
                        time.sleep(1)
                        devices = []
                        wmi = win32com.client.GetObject("winmgmts:")
                        for usb in wmi.InstancesOf("win32_usbcontrollerdevice"):
                            if "VID_2207&PID_0006" in usb.Dependent:
                                print('找到了一台ADB设备')
                            if "VID_1A86&PID_7523" in usb.Dependent:
                                print('找到了一台CH340串口设备')

                        sign.emit(devices)
                    t = Thread(target=task, args=(self.update_device,))
                    t.start()
        return tag, result

    def onUpdateDevices(self, devices):
        for i in devices:
            self.text_edit.appendPlainText(i)

    def get_serial_com(self):
        if platform.system() == 'Windows':
            port_list = list(serial.tools.list_ports.comports())
            port_list_name = []
            if len(port_list) <= 0:
                print("串口设备为空，请检查!")
            else:
                for each_port in port_list:
                    port_list_name.append(each_port[0])
            return port_list_name[0]
        else:
            return os.popen('ls /dev/tty.*usbserial*').readline().strip()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())
